package com.zhongzhi.thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.zhongzhi.common.Plc;
import com.zhongzhi.common.Primary;
import com.zhongzhi.springboot.pojo.Equipment;
import com.zhongzhi.springboot.pojo.EquipmentShow;
import com.zhongzhi.util.PlcUtil;

import lombok.Data;
import lombok.extern.log4j.Log4j;

/**
 * plc通信线程
 * @author Administrator
 *
 */
@Log4j
@Data
public class PlcThread extends Thread{

	private EquipmentShow equipment;
	private Socket socket = null;
	private InputStream inputStream = null;
	private OutputStream outputStream = null;
	
	private HashMap<String, String>	map = new HashMap<>();
	
	
	public PlcThread(EquipmentShow equipment) {
		super();
		this.equipment = equipment;
	}

	public PlcThread() {
		super();
	}

	public EquipmentShow getEquipment() {
		return equipment;
	}

	public void setEquipment(EquipmentShow equipment) {
		this.equipment = equipment;
	}

	
	private String getString() {
		Set<String> keySet = map.keySet();
		String s = "[";
		for (String string : keySet) {
			String string2 = map.get(string);
			s=s+string+":"+string2+",";
		}
		return s+"]";
	}
	/**
	 * 此线程的作用是当前电脑和plc通信,一旦通信失败,则最短半分钟回复正常.
	 */
	@Override
	public void run() {
		log.info("plc通信线程:"+this.getName()+"启动");
		HashMap<Integer, Plc> map = Primary.getMap();
		String s = "";
		
		
		PlcUtil  plcUtil = new  PlcUtil();
		while(true) {
			
			while(socket==null) {
				try {
					socket = plcUtil.getSocket(equipment);
					inputStream = socket.getInputStream();
					outputStream = socket.getOutputStream();
					socket.setSoTimeout(3000);
				} catch (IOException e) {
					log.error("无法连接plc: "+equipment.getPlcName()+" "+equipment.getHost()+":"+e);
					try {
						Thread.sleep(5000);
						map.get(equipment.getId()).setPlcState(false);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
						map.get(equipment.getId()).setPlcState(false);
					}
				} 
			}	
			try {
				String a = getString();
//				System.out.println("plc97"+a);
				
				s = plcUtil.getString(a,inputStream,outputStream);
				Map<Integer, Double> data = plcUtil.getData(s);
				map.get(equipment.getId()).getSjTemData().putAll(data);
				map.get(equipment.getId()).setPlcState(true);
				
			} catch (IOException e1) {
				try {
					outputStream.close();
					outputStream = null;
					inputStream.close();
					inputStream=null;
					socket.close();
					socket = null;
					map.get(equipment.getId()).setPlcState(false);
				} catch (IOException e) {
					e.printStackTrace();
					map.get(equipment.getId()).setPlcState(false);
				}
				log.error("重新连接plc:"+equipment.getPlcName()+" "+equipment.getHost()+"失败:"+e1);
			}
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}

}
